package com.example.demo.Aspect;

import java.io.IOException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.example.demo.Exception.ProcessException;
import com.example.demo.GeneralResponse.APIResponse;


/**
 * @version: V0.3
 * @author: 郑皓杰 吴嘉鑫
 * @className: ExceptionCatchHandler
 * @packageName: com.example.demo.Aspect
 * @description: 这是全局异常处理切面类
 * @data: 2021-07-15
 **/
@Component
@Aspect
@Order(-1)
public class ExceptionCatchHandler {
	
	@Pointcut("execution(public * com.example.demo.Controller.*.*(..))")
    public void catchControllerException(){
	}
	
    @Around("catchControllerException()")
    public Object handleControllerMethod(ProceedingJoinPoint point) throws Throwable{
    	APIResponse<?> apiResponse;
        try {
        	apiResponse = (APIResponse<?>) point.proceed(point.getArgs());
        } catch (Throwable throwable) {
        	apiResponse = handlerException(point, throwable);
        }
        return apiResponse;
    }
 
   
    
	/**
	* @author:  郑皓杰 吴嘉鑫
	* @methodsName: handlerException
	* @description: 自定义处理异常的方法
	* @param:  
	* @return: APIResponse<?>
	* @throws: 
	*/
    private APIResponse<?> handlerException(ProceedingJoinPoint point, Throwable e) {
        APIResponse<?> apiResponse = null;
        if(e.getClass().isAssignableFrom(ProcessException.class) ){
        	ProcessException processException = (ProcessException)e;
        	apiResponse = processException.getApiResponse();
        } else 	if (e instanceof IllegalArgumentException) {
        	apiResponse = APIResponse.fail("Illegal Argument: "+e.getMessage());
        } else if(e instanceof NullPointerException){
        	apiResponse = APIResponse.fail("empty result: "+e.getMessage());
        } else if(e instanceof IOException) {
        	apiResponse=APIResponse.fail("IOException: "+e.getMessage());
        }else {
        	apiResponse=APIResponse.fail("Unknown error: "+e.getMessage());
        }
        return apiResponse;
    }
}
